const { src, dest, series, parallel, watch } = require("gulp");
const autoPrefixer = require("gulp-autoprefixer");
const cleanCss = require("gulp-clean-css");
const rename = require("gulp-rename");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");
const htmlmin = require("gulp-htmlmin");
const del = require("del");
const browserSync = require("browser-sync");
const bs = browserSync.create();

//构建样式
const style = () => {
    return src("src/css/*.css", { base: "src" })
        .pipe(autoPrefixer())//兼容css hack
        .pipe(cleanCss())//压缩css
        .pipe(rename({ extname: '.min.css' }))//重命名css
        .pipe(dest("dist"));
}

//构建脚本
const script = () => {
    return src("src/js/*.js", { base: "src" })
        // .pipe(babel({
        //     presets: ['babel-preset-env']
        // }))
        // .pipe(uglify())
        // .pipe(rename({ extname: '.min.js' }))
        .pipe(dest("dist"));
}

//构建HTML
const html = () => {
    return src("src/index.html", { base: "src" })
        .pipe(htmlmin({
            collapseWhitespace: true,//折叠空白
            minifyCSS: true,//压缩HTML内的css
            minifyJS: true,//压缩HTML内的js代码
        }))
        .pipe(dest("dist"));
}

//清理任务
const clean = () => {
    return del(['dist']);
}

//发布服务
const serve = () => {
    //监视文件变化 重新构建
    watch('src/index.html', html);
    watch('src/js/*.js', script);
    watch('src/css/*.css', style);
    bs.init({
        notify: false,
        files: 'dist/**',
        server: {
            baseDir: './dist',
            routes: {
                '/node_modules': 'node_modules'
            }
        }
    });
}

const start = series(clean, parallel(style, script, html), serve);

//通过npm run dev 启动db.json,然后启动gulp
module.exports = {
    start
}